//
//  MVdetialViewController.m
//  艾听歌
//
//  Created by dllo on 16/6/4.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "MVdetialViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "MVChildModel.h"

@interface MVdetialViewController ()
@property (nonatomic, strong) UIView *playView;/**< 播放页面*/
@property (nonatomic, strong) UIView *controlView;/**< 控制台*/
@property (nonatomic, strong) UILabel *playTime;/**< 播放时间*/
@property (nonatomic, strong) UILabel *totalTime;/**< 总时间*/
@property (nonatomic, strong) UIButton *playbtn;/**< 播放按钮*/
@property (nonatomic, strong) UIButton *fullBtn;/**< 全屏*/
@property (nonatomic, strong) UISlider *progress;/**< 进度条*/

@property (nonatomic, strong) AVPlayer *player;/**< 播放器*/
@property (nonatomic, strong) AVPlayerItem *playerItem;/**< 播放对象*/
@property (nonatomic, strong) AVPlayerLayer *playerLayer;/**< 播放图层*/

@property (nonatomic, assign) BOOL isPlaying;/**< 播放状态*/

@property (nonatomic, assign) BOOL isHidden;/**< 控制台的显示/隐藏*/
@property (nonatomic, assign) CGFloat totalDuration;/**< 总时长*/

@end

@implementation MVdetialViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorPickerWithRGB(0xFF6EB4, 0x9C9C9C);
    self.view.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff, 0x9c9c9c);
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 300)];
    self.playView.backgroundColor = [UIColor yellowColor];
    
    [self.view addSubview:self.playView];
    self.controlView = [[UIView alloc] initWithFrame:CGRectMake(0, 265, WIDTH, 40)];

    self.controlView.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff, 0x9c9c9c);
    [self.playView addSubview:self.controlView];
    
    self.playbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playbtn.frame = CGRectMake(5, 10, 30, 30);
//    self.playbtn.backgroundColor = [UIColor redColor];
    
    [self.playbtn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView addSubview:self.playbtn];
    
    self.playTime = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 50, 30)];
//    self.playTime.backgroundColor = [UIColor purpleColor];
    [self.controlView addSubview:self.playTime];
    
    self.progress = [[UISlider alloc] initWithFrame:CGRectMake(90, 10, 210, 20)];

    [self.progress addTarget:self action:@selector(progressAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView addSubview:self.progress];
    
    self.totalTime = [[UILabel alloc] initWithFrame:CGRectMake(300, 10, 50, 30)];
//    self.totalTime.backgroundColor = [UIColor brownColor];
    [self.controlView addSubview:self.totalTime];
    
    
        [self createPlayer];
    self.isPlaying = NO;
//    [self.playbtn setTitle:@"pause" forState:UIControlStateNormal];
    [self.playbtn setBackgroundImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
    [self.playbtn setBackgroundImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateSelected];
    
    [self gestureControlBottomView];
    [self addListener];
    [self progressListen];
    self.progress.value = 0;
    
    
    
}
//// viewcontroller支持哪些转屏方向
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
//    
//    // MoviePlayerViewController这个页面支持转屏方向
//    return UIInterfaceOrientationMaskAllButUpsideDown;
//    
//}
+ (MVdetialViewController *)shanreMVdetailViewController
{
    static MVdetialViewController *PlayMV = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        PlayMV = [[MVdetialViewController alloc] init];
    });
    return PlayMV;
    
}
#pragma mark - 添加观察着
-(void)addListener{
    // 监听是否播放完毕
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

-(void)moviePlayDidEnd:(NSNotification *)noti{
    NSLog(@"播放结束");
    self.isPlaying = NO;
    self.playbtn.selected = self.isPlaying;
    // 播放结束后跳回到程序一开始
    [self.player seekToTime:CMTimeMake(0, 1)];
    
    
    
    
}
#pragma mark - 添加手势
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    if (!self.isHidden) {
        [self hidenControlView];
    } else {
        // 显示
        [UIView animateWithDuration:0.4 animations:^{
            self.controlView.alpha = 1;
        } completion:^(BOOL finished) {
            [self performSelector:@selector(hidenControlView) withObject:nil afterDelay:1];
            
            self.isHidden = YES;
        }];
    }
    self.isHidden = !self.isHidden;
}

-(void)gestureControlBottomView{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.playView addGestureRecognizer:tap];
}
// 隐藏底部
-(void)hidenControlView{
    // 隐藏
    [UIView animateWithDuration:0.4 animations:^{
        self.controlView.alpha = 0;
       
    }];
    
}
#pragma mark - 创建播放器
-(void)createPlayer{
    //视频网址
//    NSString *str = @"http://flv2.bn.netease.com/videolib3/1505/24/HYUCE6348/SD/HYUCE6348-mobile.mp4";
    MVChildModel *model = [self.MVurl firstObject];
//    NSLog(@"%@", model.url);
    NSString *str = model.url;
    //创建播放对象(item)
    self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:str]];
    
    // 创建播放器(player)
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    // 创建播放页面(layer)
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    // 设置layer大小
    self.playerLayer.frame = CGRectMake(5, 5, _playView.bounds.size.width - 10, self.playView.bounds.size.height - 10);
    //视频填充模式
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    //将layer投影到view上显示
    [self.playView.layer insertSublayer:self.playerLayer atIndex:0];
    
}
- (void)playAction:(UIButton *)sender
{
    
    
   
    
    if (self.isPlaying) {
        
        // 正在播放时  暂停
        [self.player pause];
    }else{
        
        // 暂停时 播放
        [self.player play];
        // 开始播放时 1s后自动隐藏底部边栏
        [self performSelector:@selector(hidenControlView) withObject:nil afterDelay:1];
        self.isHidden = YES;
    }
    // 状态取反
    self.isPlaying = !self.isPlaying;
    // 改变按钮
    sender.selected = self.isPlaying;
    
    
    
    
    
    
    
}


// 进度条监听
-(void)progressListen{
    // 让播放器监听时间的变化 把变化同步到视图上
    // 参数1: 监听器刷新时间
    // 参数2: 队列
    // 参数3: 刷新时 执行的block
    // CMTime(1,1) 每一秒刷新一次
    __weak MVdetialViewController *vc = self; // 解决block中调用外部变量容易产生循环引用
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        // 获取总时长
        CGFloat duration = CMTimeGetSeconds(vc.playerItem.duration);
        //  保存总时长(用于进度条变化)
        vc.totalDuration = duration;
        // 获取当前时长
        CGFloat current = CMTimeGetSeconds(vc.player.currentTime);
        // 剩余时间
        CGFloat sheng = duration - current;
        // 字符串转化
        NSString *curStr = [NSString stringWithFormat:@"%02d:%02d", (int)(current / 60),((int)current % 60)];
        NSString *shengStr = [NSString stringWithFormat:@"%02d:%02d", (int)(sheng / 60),((int)sheng % 60)];
        // 赋值lable
        vc.playTime.text = curStr;
        vc.totalTime.text = shengStr;
        // 赋值进度条
        vc.progress.value = current / duration;
        
    }];
}

- (void)progressAction:(UISlider *)sender
{
    [self.player pause];
    // 当前时间
    CGFloat cur = _totalDuration * sender.value;
    // 通过滑动 控制播放器跳转到对应的时间点
    [self.player seekToTime:CMTimeMake(cur, 1) completionHandler:^(BOOL finished) {
        // 跳转完成之后播放
        [self.player play];
    }];
    
}
// 视图将要出现的时候 tabBar隐藏
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
    
}
@end
